package com.hos.db.manager;

import com.gexin.rp.sdk.base.uitls.MD5Util;
import com.hos.db.create.consult.ConsultChatTable;
import com.hos.db.entity.consult.ConsultChatEntity;
import com.hos.net.req.consult.ConsultChatAddReq;
import com.hos.net.res.MsgHint;
import com.hos.operation.push.gtui.PushDoc;
import com.hos.operation.push.gtui.PushPat;
import com.hos.utile.DLog;
import com.hos.utile.DateUtile;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//咨询
public class ConsultChatManager {

    private static ConsultChatManager userPatsManager;

    public static ConsultChatManager getInstance() {
        if (userPatsManager == null) {
            userPatsManager = new ConsultChatManager();
        }
        return userPatsManager;
    }

    //添加咨询聊天
    public String onConsultChatAddReq(JdbcTemplate jdbcTemplate, ConsultChatAddReq req) {
        String response = new MsgHint("添加失败").toJson();

        String sql = "INSERT INTO " + ConsultChatTable.tableName
                + "("
                + ConsultChatTable.tableConsultId + ","
                + ConsultChatTable.tableChatId + ","
                + ConsultChatTable.tableChatSendType + ","
                + ConsultChatTable.tableChatType + ","
                + ConsultChatTable.tableChatMsg + ","
                + ConsultChatTable.tableChatImageW + ","
                + ConsultChatTable.tableChatImageH + ","
                + ConsultChatTable.tableChatSendTime
                + ")"
                + " VALUES (?,?,?, ?, ?,?, ?,?)";
        try {
            Date time = new Date();
            String t1 = DateUtile.getDateFormat(time, DateUtile.DATA_FORMAT_YMD_HMS);
            String id = MD5Util.getMD5Format(req.consultId + t1);
            int status = jdbcTemplate.update(sql,
                    new Object[]{req.consultId, id, req.consultSendType, req.consultChatType,
                            req.consultChatMsg, req.imageW, req.imageH, time});
            //修改这条咨询为进行中，并且更新回复状态
            ConsultManager.getInstance().onConsultReplyReq(jdbcTemplate,
                    req.consultId);
            if (status > 0) {
                response = new MsgHint("0", "").toJson();

                if ("doc".equals(req.consultSendType)) {
                    //是医生发送的_推送给患者
                    String pushId = PatsManager.getInstance().getPushId(jdbcTemplate, req.userId);
                    PushPat.getInstance().onConsultChat(req.userId, pushId, req.consultId,
                            req.consultChatMsg, req.consultChatType, false);
                }

                if ("pat".equals(req.consultSendType)) {
                    //是患者发送的_推送给医生
                    String pushId = DocsManager.getInstance().getPushId(jdbcTemplate, req.userId);
                    PushDoc.getInstance().onConsultChat(req.userId, pushId, req.consultId,
                            req.consultChatMsg, req.consultChatType, true);
                }
            }
        } catch (Exception e) {
            DLog.e("添加失败：" + e.getMessage());
        }
        return response;
    }


    /**
     * 获取咨询聊天
     *
     * @param jdbcTemplate
     * @param pageNo       页面（>=1）
     * @param pageSize     每页查询数量
     */

    public List<ConsultChatEntity> onConsultChats(JdbcTemplate jdbcTemplate, String consultId,
                                                  int pageNo, int pageSize, boolean hasNextPage) {
        int next = 0;
        if (hasNextPage) {
            next = 1;
        }
        //SELECT * FROM (
        //  SELECT * FROM consult_chat WHERE consult_id = '2' ORDER BY chat_send_time DESC  limit 0 , 31
//) temp ORDER BY temp.chat_send_time asc
        String w = " WHERE " + ConsultChatTable.tableConsultId + " = '" + consultId + "'";
        String childs = "SELECT * FROM " + ConsultChatTable.tableName
                + w
                + " ORDER BY " + ConsultChatTable.tableChatSendTime
                + " DESC "
                + " limit "
                + (pageNo - 1) * pageSize + " , " + (pageSize + next);
        String sql = " SELECT * FROM ( " + childs + " ) "
                + " temp " + " ORDER BY "
                + " temp."
                + ConsultChatTable.tableChatSendTime
                + " asc ";
        List<ConsultChatEntity> cons = onChat(jdbcTemplate, sql);
        if (cons == null) {
            cons = new ArrayList();
        }
        return cons;
    }

    //查询聊天
    private List<ConsultChatEntity> onChat(JdbcTemplate jdbcTemplate, String sql) {
        List<ConsultChatEntity> cons = null;
        try {
            cons = jdbcTemplate.query(sql,
                    ParameterizedBeanPropertyRowMapper.newInstance(ConsultChatEntity.class));
            DLog.e("查询成功：==========");
        } catch (Exception e) {
            DLog.e("查询失败：" + e.getMessage());
        }
        return cons;
    }

}
